/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *SdProjectAppointmentController
 * SD项目任命
 *
 * 修改纪录
 * 2021-12-14 版本：1.0 jiangtao 创建。
 * @version 版本：1.0
 * @author 作者：jiangtao
 * 创建日期：2021-12-14
 */

package com.topscomm.gpm.controller;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.service.ICboAttachmentService;
import com.topscomm.gpm.controller.auto.GpmProjectAppointmentControllerAuto;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.service.impl.MmsDeptExtraInfoService;
import com.topscomm.pub.util.*;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.service.impl.GpmProjectService;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pub.vo.ResponseResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: jiangtao
 * @date: 2021-12-14
 * @description:SD项目任命Controller
 * @modify:
 */
@RestController
@RequestMapping("sd/projectAppointment")
public class GpmProjectAppointmentController extends GpmProjectAppointmentControllerAuto implements IGpmProjectAppointmentController {
	@Autowired
	private GpmProjectService gpmProjectService;
	@Autowired
	private ICboAttachmentService cboAttachmentService;
	@Autowired
	private MmsDeptExtraInfoService mmsDeptExtraInfoService;

	/**
	 * @author: jiangtao
	 * @date: 2021-12-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and  projectid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and  projectcode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
//			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
//			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
//			{
//				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
//				if (StringUtil.isEmpty(deptcodes_header))
//					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
//							.getUserBean().getWorkDept().getCode());
//				else
//					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
//							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
//			} else// 使用数据权限
//			{
//				sql.appendSingle(" and {0} ", dataPession);
//			}
		}
		return sql.toString();
	}

	/**
	 * @author: jiangtao
	 * @date: 2021-12-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: jiangtao
	 * @date: 2021-12-14
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交GPM项目任命申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}

	@PutMapping({"/approval"})
	@Override
	public ResponseResult<Object> approval(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String approvalOpinion = paraMap.get("approvalopinion").toString();
			String approvalType = paraMap.get("approvaltype").toString();
			String nodeInsId = paraMap.get("nodeinsid").toString();
			String backNodeId = ConvertUtil.convertToString(paraMap.get("backnodeid"));
			long nextUserId = 0L;
			if (paraMap.containsKey("nextuserid") && !StringUtil.isEmpty(paraMap.get("nextuserid").toString())) {
				nextUserId = Long.parseLong(paraMap.get("nextuserid").toString());
			}
			if ("".equals(approvalOpinion) && "1".equals(approvalType)) {
				approvalOpinion = "同意";
			}
			this.service.executeApprove(nodeInsId, new Date(), approvalOpinion, approvalType, backNodeId, this.getUserBean(), nextUserId);
			return ResponseResult.ok("操作成功");
		} catch (Exception var8) {
			return this.handleControllerException(var8);
		}
	}


	@PostMapping({"/generateAppointment"})
	public ResponseResult<Object> generateAppointment(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.generateAppointment(paraMap);
			return ResponseResult.ok("操作成功");
		} catch (Exception var8) {
			return this.handleControllerException(var8);
		}
	}

	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		String projectCode = ConvertUtil.convertToString(paraMap.get("projectcode"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" projectcode = '{0}' ", projectCode);
		List<GpmProjectEntity> mpmProjectInfoList = gpmProjectService.queryByWhere(sql.toString());
		if (CollectionUtils.isEmpty(mpmProjectInfoList)) {
			return;
		}
		GpmProjectEntity mpmProjectInfo = mpmProjectInfoList.get(0);
		paraMap.put("projectname", mpmProjectInfo.getProjectname());
		paraMap.put("projectcreateon", mpmProjectInfo.getCreateon());
	}

	@PostMapping(value = "/download")
	public void download(@RequestBody Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Map<String, Object> resultMap = this.service.executeDownload(paraMap);
			// 设置文件名字(给要下载文件重命名);
			String fileName = ConvertUtil.convertToString(resultMap.get("attFileName"));
			response.setContentType("application/octet-stream");
			// response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			InputStream inStream = BaseUtil.convertByteToStream((byte[]) resultMap.get("attInputStream"));
			OutputStream outStream = response.getOutputStream();
			byte[] bytes = new byte[2048];
			int len;
			while ((len = inStream.read(bytes)) != -1) {
				outStream.write(bytes, 0, len);
			}
			inStream.close();
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	@PostMapping({"/sendmail"})
	public ResponseResult<Object> sendmail(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.sendMessage(ConvertUtil.convertToString(paraMap.get("appointid")));
			return ResponseResult.ok("操作成功");
		} catch (Exception var8) {
			return this.handleControllerException(var8);
		}
	}

	@GetMapping({"/checkappointcount"})
	public ResponseResult<Object> checkappointcount(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			String projectCode = ConvertUtil.convertToString(paraMap.get("projectcode"));
			List<Map<String, Object>> maps = this.service.selectExecute(" select count(id) as count from GPMProjectAppointment where projectcode = '" + projectCode + "'");
			int count = ConvertUtil.convertToInt(maps.get(0).get("count"));
			Map<String, Object> result = new HashMap<>();
			result.put("isFirstAppoint", count == 0);
			return ResponseResult.ok(result);
		} catch (Exception var8) {
			return this.handleControllerException(var8);
		}
	}

	@PostMapping(value = "/upload")
	public ResponseResult<Object> upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Map<String, Object> paraMap) {
		File attachFile = null;
		try {

			if (file == null || file.getSize() <= 0)
				return ResponseResult.error("找不到合法的文件");
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			attachFile = multipartFileToFile(file);
			// 先删除之前的附件
			String sourceId = ConvertUtil.convertToString(paraMap.get("sourceId"));
			cboAttachmentService.deleteByWhere(" sourcetype = 'MpmProjectAppointmentGenerate' and sourceid = " + sourceId);
			Map<String, Object> map = this.cboAttachmentService.executeUpload(paraMap, attachFile);

			return ResponseResult.ok(map);
		} catch (Exception e) {
			return ResponseResult.error(e.getMessage());
		} finally {
			if (attachFile != null)
				if(!attachFile.delete()) {
				System.out.print("文件删除出错");
				}
		}
	}

	/**
	 * @author zhanglongfei
	 * @date 2020年2月12日
	 * @description upload获取到的文件转换
	 * @param file
	 * @return
	 * @throws Exception
	 */
	private File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file == null || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}

	// 获取流文件
	private void inputStreamToFile(InputStream ins, File file) throws IOException {
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				os.close();
			}
			if (ins != null) {
				ins.close();
			}
		}
	}
}

